import os
import sys
import pandas as pd
from tabulate import tabulate
from pathlib import Path

def excel_to_markdown(excel_file, output_dir):
    """将Excel文件转换为Markdown格式"""
    try:
        # 读取Excel文件
        print(f"正在处理: {excel_file}")
        # 获取所有工作表
        excel = pd.ExcelFile(excel_file)
        sheet_names = excel.sheet_names
        
        # 创建输出文件名
        base_name = os.path.basename(excel_file)
        output_file = os.path.join(output_dir, f"{os.path.splitext(base_name)[0]}.md")
        
        with open(output_file, 'w', encoding='utf-8') as md_file:
            # 写入文件标题
            md_file.write(f"# {os.path.splitext(base_name)[0]}\n\n")
            
            # 处理每个工作表
            for sheet_name in sheet_names:
                df = pd.read_excel(excel_file, sheet_name=sheet_name)
                
                # 写入工作表名称
                md_file.write(f"## 工作表: {sheet_name}\n\n")
                
                # 将数据转换为Markdown表格
                markdown_table = tabulate(df, headers='keys', tablefmt='pipe', showindex=False)
                md_file.write(markdown_table)
                md_file.write("\n\n")
                
        return output_file
    except Exception as e:
        print(f"处理文件 {excel_file} 时出错: {str(e)}")
        return None

def main():
    # 设置目录路径
    target_dir = r"E:\python_out\output_0801"
    output_dir = os.path.join(target_dir, "markdown_output")
    
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)
    
    # 获取所有Excel文件
    excel_files = [os.path.join(target_dir, f) for f in os.listdir(target_dir) 
                  if f.endswith('.xlsx') and os.path.isfile(os.path.join(target_dir, f))]
    
    print(f"发现 {len(excel_files)} 个Excel文件")
    
    # 转换每个文件
    successful_files = []
    for excel_file in excel_files:
        output_file = excel_to_markdown(excel_file, output_dir)
        if output_file:
            successful_files.append(output_file)
    
    print(f"\n转换完成! {len(successful_files)}/{len(excel_files)} 个文件成功转换为Markdown格式。")
    print(f"输出文件位置: {output_dir}")

if __name__ == "__main__":
    main() 